package psico_test.utils.bd;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class BDManager 
{
	public static BDManager instance;

	private Connection con;

	public static BDManager getInstance() 
	{
		if(instance==null)
			instance = new BDManager();
		return instance;
	}

	private BDManager()
	{
		try
		{
			this.InicializarBaseDeDatos();
		}
		catch(Exception e)
		{
			System.out.println("La base de datos ya está inicializada");
		}	
	}

	private void conectarBD() 
	{
		try
		{
			Class.forName("org.sqlite.JDBC");
			con = DriverManager.getConnection("jdbc:sqlite:/home/asier/Psico-Test/Usuarios/users.sqlite");
		}catch(Exception e)
		{
			try{Runtime.getRuntime().exec("killall -9 java");}
			catch(Exception ex){System.out.println(ex.getMessage());}

			System.exit(0);
		}
	}

	public void desconectarBD()
	{
		try{
			con.close();
		}catch(Exception e){}
	}

	private void InicializarBaseDeDatos() throws SQLException
	{
		//si no hay conexión se crea
		if(con.isClosed())
			conectarBD();
		
		con.prepareStatement("CREATE TABLE Administradores(username,pass)").execute();
		con.prepareStatement("CREATE TABLE Clientes(nombre,apellido,dni,telefono,edad)").execute();

		con.setAutoCommit(false);

		PreparedStatement ps1 = con.prepareStatement("INSERT INTO Administradores values(?,?)");
		ps1.setString(1,"admin");
		ps1.setString(2,"admin");
		ps1.addBatch();
		ps1.setString(1,"root");
		ps1.setString(2,"admin");
		ps1.addBatch();
		ps1.executeBatch();
		con.commit();
		ps1.close();

		PreparedStatement ps2 = con.prepareStatement("INSERT INTO Clientes values(?,?,?,?,?)");
		ps2.setString(1,"Asier");
		ps2.setString(2,"Orbe");
		ps2.setString(3,"45752232-B");
		ps2.setString(4,"679845188");
		ps2.setString(5,"21");
		ps2.addBatch();
		ps2.setString(1,"Julen");
		ps2.setString(2,"Iriarte");
		ps2.setString(3,"45678391-Z");
		ps2.setString(4,"629556336");
		ps2.setString(5,"22");
		ps2.addBatch();
		ps2.executeBatch();
		con.commit();
		ps2.close();

		con.close();
	}

	public synchronized boolean autentificar(String username, char[] pass)
	{
		return true;
	}

	//debugger
	public static void main(String []args)
	{
		BDManager.getInstance();
	}
}
